<?php
declare(strict_types=1);

namespace App\Controller\Admin\V1\Cms;

use App\Controller\Admin\AdminController;
use App\Repositories\CmsCategoryRepository;
use App\Request\CmsCategoryRequest;

class CategoryController extends AdminController
{
    public function select()
    {
        $top = (int)$this->request->input('top',1);//是否展示顶级
        $line = (int)$this->request->input('line',1);//是否展示树形线
        $return = CmsCategoryRepository::getInstance()->view($top,$line);
        return $this->response->success($return);
    }

    public function detail()
    {
        $model = CmsCategoryRepository::getInstance()->getById($this->request->input('id'));
        return $this->response->success($model);
    }

    public function list()
    {
        $parent_id = $this->request->input('parent_id',0);
        $search = [
            ['field'=>'parent_id','value'=>$parent_id]
        ];
        $orderBy= [
            [
                'field' => 'id',
                'sort' => 'asc'
            ]
        ];
        $datas = CmsCategoryRepository::getInstance()->getList('*',$search,['limit'=>10000],$orderBy);
        foreach ($datas['result'] as $key=>$data){
            if($data['rgt']-$data['lft']>1){
                $datas['result'][$key]['children']=[];
            }
        }
        return $this->response->success($datas);
    }

    public function store(CmsCategoryRequest $request)
    {
        $result = CmsCategoryRepository::getInstance()->store($request->all());
        if($result['success']){
            return $this->response->success($result['data']);
        }
        return $this->response->error(10000,$result['msg']);
    }

    public function delete()
    {
        $id = $this->request->input('id');
        $result = CmsCategoryRepository::getInstance()->delete($id);
        if($result['success']){
            return $this->response->success($result['data']);
        }
        return $this->response->error(10000,$result['msg']);
    }
}
